<template>
    <div>
        <el-dialog title="数据录入" :visible.sync="dialogVisible" width="80%" v-dialogDrag v-loading="loading"
        element-loading-text="计算中，请稍后" :before-close="closeDialog">
            <div class="table-tips">📝 双击单元格进行数据录入，支持框选复制粘贴，右键菜单提供配置选项，编辑完成后请及时保存。</div>
            <ve-table
                fixed-header
                max-height="calc(100vh - 400px)"
                :columns="tableColumns"
                :table-data="tableDialogList"
                rowKeyFieldName="row"
                :rowStyleOption="rowStyleOption"
                :clipboard-option="clipboardOption"
                :cell-autofill-option="cellAutofillOption"
                :edit-option="editOption"
                :contextmenu-body-option="contextmenuBodyOption"
                border-y
                ref="tableRef"
            />
            <div class="dialog-footer">
                <el-button type="success"  @click="handleinsertPointCalc" size="small" icon="el-icon-connection" class="confirm-btn">计算</el-button>
                <el-button type="primary"  @click="handleSaveDialogTable" size="small" icon="el-icon-circle-check" class="confirm-btn">保存配置</el-button>
            </div>
        </el-dialog>
        <el-dialog  :visible.sync="addRowDialogVisible" width="360px" v-dialogDrag>
            <div>
            追加行数：<el-input-number v-model="num" :min="2" label="请输入" size="small"></el-input-number>
            <el-alert style="margin-top:10px"
                title="数字越大，系统加载越慢，请按需输入"
                type="warning" :closable="false">
            </el-alert>
            </div>
            <div class="dialog-footer">
                <el-button size="small" @click="addRowDialogVisible = false" class="cancel-btn" icon="el-icon-circle-close">取消</el-button>
                <el-button type="primary" size="small" @click="addRowClick" icon="el-icon-circle-check" class="confirm-btn">保存配置</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {GetInsertCOMP,insertPointCalc,insertPointSave} from "@/api/https";
export default {
    props:{
        visible:{
            type:Boolean,
            default:false
        },
        stationId:{
            type:[String,Number],
            default:''
        },
        treeID:{
            type:Number,
            default:0
        },
        CodeId:{
            type:Number,
            default:0
        },
        instRID:{
            type:Number,
            default:0
        }
    },
    data() {
        return {
            unwatchTableList: null,
            addRowDialogVisible:false,
            loading:false,
            num:1,
            dialogVisible:this.visible,
            tableColumns:[],
            tableDialogList:[],
            rowStyleOption: {
                clickHighlight: false,
                hoverHighlight: true,
            },
            clipboardOption:{
                copy: true,
                paste: true,
                cut: true,
                delete: true,
            },
            cellAutofillOption: {
                directionX: false,
                directionY: true,
            },
            editOption: {
                createNewRow: () => {
                    const newRow = {
                        pointName: '',
                        watchtime: '',
                        remark: '',
                    };
                    this.tableDialogTitle.forEach(item => {
                        newRow[item.insertValue] = '';
                    });
                    return newRow;
                },
                afterCellValueChange: ({ row, column, changeValue }) => {  
                   
                },
            },
            contextmenuBodyOption: {
                contextmenus: [
                    {
                        type: "CUT",
                    },
                    {
                        type: "COPY",
                    },
                    {
                        type: "SEPARATOR",
                    },
                    {
                        type: "INSERT_ROW_ABOVE",
                    },
                    {
                        type: "INSERT_ROW_BELOW",
                    },
                    {
                        type:'addRowMore',
                        label:'追加多行'
                    },
                    {
                        type: "SEPARATOR",
                    },
                    {
                        type: "REMOVE_ROW",
                    },
                    {
                        type: "EMPTY_ROW",
                    },
                    {
                        type: "EMPTY_CELL",
                    },
                ],
                afterMenuClick: ({ type }) => {
                    if(type == 'addRowMore'){
                        this.addRowDialogVisible = true;
                    }
                },
            },
            tableDialogTitle:[],
            startRowIndex:0,
        }
    },
    watch: {
        visible(newVal) {
            this.dialogVisible = newVal;
            if(newVal) {
                this.getDialogData();
            }
        },
        dialogVisible(newVal) {
            this.$emit('update:visible', newVal);
        }
    },
    mounted() {
        this.unwatchTableList = this.$watch('tableDialogList',(newVal) => {
            newVal.forEach((row, index) => {
                this.$set(row, 'row', index + 1);
            });
        },{ deep: true })
    },
    beforeDestroy() {
        if (this.unwatchTableList) {
            this.unwatchTableList();
        }
        this.clearData()
    },
    computed: {
        itemTypeList() {
            return this.tableDialogTitle
            .filter(item => item.itemType === 0)
            .map(item => item.insertValue);
        }
    },
    methods:{
        getDialogData(){
            GetInsertCOMP({
                treeId:this.treeID,
                stationId:this.stationId,
                codeId:this.CodeId
            }).then(res =>{
                if(res.isSuccess && res.data){
                    this.tableDialogTitle = res.data;
                    const _listTitle = [];
                    _listTitle.push({
                        field: "row",
                        key: "row",
                        operationColumn: true,
                        title: "序号",
                        width: 50,
                        fixed: "left",
                        renderBodyCell: ({ row, column, rowIndex }, h) => {
                            return rowIndex + this.startRowIndex + 1;
                        },
                    },{
                        title:'测点名称',
                        field:'pointName',
                        key:'pointName',
                        edit:true
                    },{
                        title:'观测日期',
                        field:'watchtime',
                        key:'watchtime',
                        edit:true
                    });
                    
                    if(res.data.length > 0){
                        res.data.forEach(item=>{
                            _listTitle.push({
                                title:item.insertName,
                                field:item.insertValue,
                                key:item.insertValue,
                                edit:true
                            });
                        });
                    }
                    
                    _listTitle.push({
                        title:'备注',
                        field:'remark',
                        key:'remark',
                        edit:true
                    });
                    
                    this.tableColumns = [..._listTitle];
                    this.tableDialogList = [];
                    
                    for (let i = 0; i < 50; i++) {
                        const dataItem = {
                            row: i+1,
                            pointName: '',
                            watchtime: '',
                            remark: '',
                        };
                        res.data.forEach(item=>{
                            dataItem[item.insertValue] = '';
                        });
                        this.tableDialogList.push(dataItem);
                    }
                }else{
                    this.$message.error(res.errorMessage);
                }
            });
        },
        addRowClick(){
            const newRows = [];
            for (let i = 1; i <= this.num; i++) {
                const newRow = {
                    pointName: '',
                    watchtime: '',
                    remark: '',
                };
                
                this.tableDialogTitle.forEach(item => {
                    newRow[item.insertValue] = '';
                });
                
                newRows.push(newRow);
            }
            
            this.tableDialogList = [...this.tableDialogList, ...newRows];
            this.addRowDialogVisible = false;
        },
        handleinsertPointCalc(){
            const _list = [];

            this.tableDialogList.forEach(item=>{
                if(item.row != 0 && item.pointName.trim() != ''){
                    const _d = {
                        pointName:item.pointName,
                        remark:item.remark,
                        row:item.row,
                        watchtime:item.watchtime
                    };
                    this.itemTypeList.forEach(key => {
                        if (item[key] !== undefined) {
                            _d[key] = item[key];
                        }
                    });
                    _list.push(_d);
                }
            });
            
            if(_list.length > 0){
                this.loading = true;
                const _data = {
                    statioN_ID:this.stationId,
                    data:_list,
                    comPs:this.tableDialogTitle,
                    INSTR_ID:this.instRID,
                    isHeartWall:false
                };
                insertPointCalc(_data).then(res=>{
                    if(res.isSuccess &&  res.data && res.data.data){
                        this.tableDialogList = res.data.data;
                        this.loading = false;
                    }else{
                        this.loading = false;
                        this.$message.error(res.errorMessage);
                    }
                });
            }else{
                this.$message.error('没有输入数据，无法计算！');
            }
        },
        handleSaveDialogTable(){
            const _list = [];
            this.tableDialogList.forEach((item,index)=>{
                if(item.row && item.pointName.trim() != ''){
                    item.INSTR_ID = this.instRID;
                    const trimmedItem = {};
                    for (const key in item) {
                        if(key == 'row' || key == 'index'){
                            trimmedItem.index = index + 1;
                        }else{
                            if (Object.prototype.hasOwnProperty.call(item, key)) {
                                if (typeof item[key] === 'string') {
                                    trimmedItem[key] = item[key].trim(); 
                                } else {
                                    trimmedItem[key] = item[key];
                                }
                            }
                        }
                    }
                    _list.push(trimmedItem);
                }
            });
            
            if(_list.length > 0){
                const _data = {
                    statioN_ID:this.stationId,
                    data:_list,
                    comPs:this.tableDialogTitle,
                    INSTR_ID:this.instRID
                };
                insertPointSave(_data).then(res=>{
                    if(res.isSuccess && res.data){
                        let err = [];
                        let success = [];
                        let message = '';
                        if(res.data.length > 0 ){
                            res.data.forEach(item=>{
                                if(item.state <= 0){
                                    err.push(item.state);
                                    message += `<p style="line-height:30px">${item.message}</p>`;
                                }else{
                                    success.push(item.state);
                                }
                            });
                        }
                        if(err.length > 0){
                            this.$message({
                                type:'error',
                                dangerouslyUseHTMLString: true,
                                message: message
                            });
                        }else{
                            this.clearData()
                            this.$emit('handleSaveDialogTable');
                        }
                    }else{
                        this.$message.error(res.errorMessage);
                    }
                });
            }else{
                this.$message.error('没有输入数据，无法保存！');
            }
        },
        closeDialog(){
            const hasData = this.tableDialogList.some(item => 
                item.row && item.pointName && item.pointName.trim() !== ''
            );
            if (hasData) {
                 this.$confirm(
                    `您当前有录入的数据尚未保存，是否需要保存？`,'提示',{ 
                        type: 'warning',
                        confirmButtonText: '保存',
                        cancelButtonText: '不保存',
                    }
                ).then(() => {
                    this.handleSaveDialogTable()
                }).catch(() => {
                    this.clearData()
                });
            }else{
                this.clearData()
            }
            
        },
        clearData(){
            this.dialogVisible = false;
            this.$nextTick(() => {
                this.tableDialogList = [];
                this.tableDialogTitle = [];
                this.tableColumns = [];
            });
        }
    }
}
</script>

<style scoped>

</style>